﻿using System;
using System.Configuration;

namespace Fuse8.DomainFramework.Configuration
{
    /// <summary>
    /// 
    /// </summary>
    public static class DataRepositoryConfiguration
    {
        private const string SqlConnectionStringKey = "CurrentSqlConnection";

        private const string SqlConnectionCreationBehaviourKey = "AlwaysCreateNewConnection";

        /// <summary>
        /// 
        /// </summary>
        public static string SqlConnectionString
        {
            get
            {
                string result = string.Empty;

                if (ConfigurationManager.AppSettings[SqlConnectionStringKey] != null)
                {
                    result = (ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings[SqlConnectionStringKey]] ??
                        new ConnectionStringSettings()).ConnectionString;
                }

                if (string.IsNullOrEmpty(result))
                {
                    throw new ConfigurationErrorsException("CurrentSqlConnection isn't defined");
                }

                return result;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static bool AlwaysCreateSqlConnection
        {
            get
            {
                bool result = true;

                if (ConfigurationManager.AppSettings[SqlConnectionCreationBehaviourKey] != null)
                {
                    if (!bool.TryParse(ConfigurationManager.AppSettings[SqlConnectionCreationBehaviourKey], out result))
                    {
                        throw new ConfigurationErrorsException("SqlConnectionCreationBehaviour isn't properly defined");
                    }
                }

                return result;
            }
        }
    }
}
